<!--
  功能：考试管理
  作者：licy
  邮箱：licy@briup.com
  时间：2021年01月13日 14:14:44
  版本：v1.0
  修改记录：
  修改内容：
  修改人员：
  修改时间：
-->
<template>
  <div class='exam_list'>
    <!-- 按钮区域 -->
    <div class="btns">
      <el-row>
        <el-col :span="16">
          <el-form inline size="small">
            <el-form-item label="名称">
              <el-input v-model="param.name" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="loadExams">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" style="text-align:right">
          <el-button type="primary" size="small" @click="toSaveHandler">新 增 考 试</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 按钮区域结束 -->
    <!-- 表格 -->
    <el-table size="small" :data="examData.list" v-loading="loading">
      <el-table-column label="序号" type="index" :index="1" fixed="left"></el-table-column>
      <el-table-column label="名称" prop="name"  min-width="340" fixed="left"> </el-table-column>
      <el-table-column label="考试类型" prop="examType" align="center" width="100"> </el-table-column>
      <el-table-column label="状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.beginTime > new Date().getTime()">未开始</el-tag>
          <el-tag size="mini" v-else-if="scope.row.endTime < new Date().getTime()">已结束</el-tag>
          <el-tag size="mini" v-else>考试中</el-tag>
        </template>  
      </el-table-column>
      <el-table-column label="参与人数" prop="numStudent" width="100" align="center"> </el-table-column>
      <el-table-column  label="考试时间" width="300" align="center">
        <template slot-scope="scope">
          {{scope.row.beginTime | fmtTime}} ~ {{scope.row.endTime | fmtTime}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="toDeleteHandler(scope.row)">删除</el-button>
          <el-button type="text" size="mini" @click="toDetailsHandler(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 表格结束 -->
    <!-- 分页 -->
   <div class="page">
      <el-pagination background 
        layout="prev, pager, next,sizes" 
        small
        :total="examData.total" 
        :page-size="examData.pageSize" 
        :current-page="examData.page"
        :page-sizes="[5, 10, 15, 20]"
        @size-change="handleSizeChange"
        @current-change="currentChangeHandler">
      </el-pagination>
   </div>
    <!-- 分页 -->
    <!-- 抽屉 -->
    <Briupdrawer :drawer-visible="visible" :title="title" width="50%" @on-change-visible="handlerVisibleChange" >
      <div slot="content">
        <el-form :model="form" ref="examForm" :rules="rules" label-width="100px" size="mini">
          <div class="sub_title">考试信息</div>
          <el-form-item label="考试名称" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="考试说明" prop="introduce">
            <el-input type="textarea" :rows="2" v-model="form.introduce"></el-input>
          </el-form-item>
          <div class="sub_title">考试内容</div>
          <el-form-item label="试卷类型" prop="examType">
            <el-select v-model="form.examType" >
              <el-option value="阶段考试" label="阶段考试"></el-option>
              <el-option value="招聘考试" label="招聘考试"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试试卷" prop="paperId">
            <el-select v-model="form.paperId" >
              <el-option v-for="paper in paperData.list" :key="paper.id" :value="paper.id" :label="paper.name"></el-option>
            </el-select>
          </el-form-item>
          <div class="sub_title">考试设置</div>
          <el-form-item label="阅卷设置" prop="isinspection">
            <el-radio-group v-model="form.isinspection">
              <el-radio :label="1">需手动阅卷</el-radio>
              <el-radio :label="0">全自动阅卷</el-radio>
            </el-radio-group>
            <div v-if="form.isinspection == 1" style="color:red;font-size:10px">
              客观题系统自动计算成绩，主观题需要老师手动评阅
            </div>
            <div v-if="form.isinspection == 0"  style="color:red;font-size:10px">
              试卷中仅包含客观题，系统自动计算成绩，无需老师手动评阅
            </div>
          </el-form-item>
          <el-form-item label="参与班级" prop="clazzIds" v-if="form.examType=='阶段考试'">
            <el-cascader filterable v-model="form.clazzIds" clearable :options="directionClazzTree" placeholder="请选择班级"
          :props="{ children:'clazzes',label:'name',value:'id',emitPath: false,multiple:true}" ></el-cascader>
          </el-form-item>
          <el-form-item label="参与学生" prop="clazzIds" v-if="form.examType=='招聘考试'">
            <el-button type="text" @click="downloadTemplateHandler">下载模板</el-button>
            <el-upload
              ref="upload"
              :auto-upload="false"
              class="upload-demo"
              :on-success="successSubmitHandler"
              drag
              :data="form"
              action="http://218.4.196.178:8008/exam/exam/saveRecruitExam"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip" style="text-align:left;color:red;font-size:12px">
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="开放时间" prop="range">
            <el-date-picker
              v-model="form.range"
              type="datetimerange"
              value-format="timestamp" 
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="防作弊设置">
            <el-select v-model="form.fzb" clearable>
              <el-option label="题目乱序" value="题目乱序"></el-option>
              <el-option label="选项乱序" value="选项乱序"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="阅卷人" prop="professorIds">
            <el-select v-model="form.professorIds" clearable :multiple=true>
              <el-option v-for="e in employeeData.list" :key="e.id" :label="e.realname" :value="e.id"></el-option>
            </el-select>
          </el-form-item>
           -->
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="visible = false">取消</el-button>
        <el-button size="small" type="primary" @click="submitHandler">确定</el-button>
      </span>
    </Briupdrawer>
    <!-- 抽屉结束 -->
  </div>
</template>

<script>
import {get,post,download} from '@/utils/request'
import _ from 'lodash'
import {mapGetters} from 'vuex'
export default {
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data () {
   return {
    visible:false,
    loading:false,
    title:"",
    param:{
      page:1,
      pageSize:10
    },
    examData:{ list:[] },
    paperData:{list:[]},
    fileList:[],
    form:{},
    employeeData:{list:[]},
    rules:{
      name: [ { required: true, message: '请输入考试名称', trigger: 'blur' } ],
      introduce: [ { required: true, message: '请输入考试介绍', trigger: 'blur' } ],
      paperId: [ { required: true, message: '选择考试试卷', trigger: 'blur' } ],
      range: [ { required: true, message: '选择考试试卷', trigger: 'blur' } ],
      isinspection: [ { required: true, message: '选择阅卷方式', trigger: 'change' } ],
      // clazzIds: [ { required: true, message: '选择考试班级', trigger: 'blur' } ],
      // professorIds: [ { required: true, message: '选择阅卷老师', trigger: 'blur' } ],
      examType: [ { required: true, message: '选择考试类型', trigger: 'blur' } ],
    },
   }
  },
  // 计算属性
  computed: {
    ...mapGetters(['directionClazzTree'])
  },
  // 侦听器
  watch: {
    "form.range":function(range){
      this.$set(this.form,'beginTime',range[0])
      this.$set(this.form,'endTime',range[1])
      console.log(this.form);
    }
  },
  // 组件方法
  methods: {
    // 下载模板
    downloadTemplateHandler(){
      let url = "/exam/exam/downloadRecruitExamStudentTemplate"
      download(url);
    },
    // 导入成功
    successSubmitHandler(response){
      if(response.status === 200){
        this.$message({ message: response.message, type: 'success' })
        this.loadExams();
        this.visible = false;
      } else {
        this.$message({ message: response.message, type: 'error' })
      }
    },
     // 查询讲师信息
    loadEmployees(){
      // 添加loading,页面加载开始
      this.loading = true;
      let url = "/employee/pageQuery"
      get(url,{
        page:1,
        pageSize:10,
        deptId:1  //教学部
      }).then(response => {
        this.employeeData = response.data;
        // 页面加载结束
        this.loading = false;
      })
    },
    // 上传成功
    uploadSuccessHandler(response){
      if(response.status == 200){
        this.$set(this.form,'photo',response.data.id);
      } else {
        this.$message({type:'error',message:'附件服务器异常！'})
        this.visible = false;
      }
    },
    // 确认提交处理函数
    submitHandler(){
      // 表单校验
      this.$refs['examForm'].validate((valid) => {
        if (valid) {
          switch(this.form.examType){
            case "阶段考试":
              // 校验通过后，完成数据交互
              let url = '/exam/exam/saveOrUpdate'
              let form = _.clone(this.form);
              if(form.range){
                form.beginTime = form.range[0];
                form.endTime = form.range[1]
                delete form.range;
              }
              // 发送请求
              post(url,form).then(response => {
                this.$message({type:"success",message:response.message})
                this.loadExams();
                this.visible = false;
              })
              break;
            case "招聘考试":
              this.$refs.upload.submit();
              break;
          }
          
        } else {
          return false;
        }
      });
    },
    // 去保存
    toSaveHandler(){
      this.title = "新增考试信息";
      this.form = {
        examType:"阶段考试"
      };
      this.fileList = [];
      this.visible = true;
    },
    // 去修改
    toDetailsHandler(row){
      this.form = _.clone(row);
      // 跳转到详情
      this.$router.push({
        path:"/sms/professor/exam/ExamDetails",
        query:{id:row.id}
      })
    },
    // 去删除
    toDeleteHandler(row){
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = '/exam/exam/deleteById'
        get(url,{id:row.id}).then(response =>{
          this.$message({ type: 'success', message: '删除成功!' });
          this.loadExams();
        })
      })
    },
    // 查询试卷信息
    loadPapers(){
      // 添加loading,页面加载开始
      let url = "/exam/paper/pageQuery"
      get(url,{page:1,pageSize:100}).then(response => {
        this.paperData = response.data;
      })
    },
    // 查询考试信息
    loadExams(){
      // 添加loading,页面加载开始
      this.loading = true;
      let url = "/exam/exam/pageQuery"
      get(url,this.param).then(response => {
        this.examData = response.data;
        // 页面加载结束
        this.loading = false;
      })
    },
    // 当前页发生改变
    currentChangeHandler(page){
      this.param.page = page;
      this.loadExams();
    },
    // 处理分页大小变化的函数
    handleSizeChange(pageSize){
      // 当前页为第一页
      this.page = 1;
      // 页面大小为用户选择的页面
      this.param.pageSize = pageSize;
      this.loadExams();
    },
    // 重置表单校验
    clearValidate() {
      this.$refs['examForm'].clearValidate();
    },
    // 处理visible变化的钩子函数，解决抽屉无法收缩的bug
    handlerVisibleChange(val) {
      this.visible = val
    }
  },
  // 以下是生命周期钩子
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created () {
    // 加载考试信息
    this.loadExams();
    // 加载试卷信息
    this.loadPapers();
    // 教师
    this.loadEmployees();
  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted () {
  },
  /**
  * 实例销毁之前调用。在这一步，实例仍然完全可用。
  */
  beforeDestroy () {
  },
  /**
  * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
  * 所有的事件监听器会被移除，所有的子实例也会被销毁。
  */
  destroyed () {
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<!--使用了scoped属性之后，父组件的style样式将不会渗透到子组件中，-->
<!--然而子组件的根节点元素会同时被设置了scoped的父css样式和设置了scoped的子css样式影响，-->
<!--这么设计的目的是父组件可以对子组件根元素进行布局。-->
<style scoped>

</style>
